package com.cloudsigns.factorymanager2.produce.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cloudsigns.factorymanager2.BaseActivity;
import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.IUploadPhotoView;
import com.cloudsigns.factorymanager2.engineering.bean.DialogItemBean;
import com.cloudsigns.factorymanager2.engineering.customview.AddProductInforPoupWindow;
import com.cloudsigns.factorymanager2.engineering.customview.BottomListDialog;
import com.cloudsigns.factorymanager2.engineering.presenter.UploadPhotoPresenter;
import com.cloudsigns.factorymanager2.engineering.utils.PhotoUtil;
import com.cloudsigns.factorymanager2.produce.bean.Produce_ProductBean;
import com.cloudsigns.factorymanager2.project.myinerface.ItemClickListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ProduceAddProductInfomationActivity extends BaseActivity implements ItemClickListener, CompoundButton.OnCheckedChangeListener,
        BottomListDialog.OnItemDialogClick, IUploadPhotoView {

    private String TAG = ProduceAddProductInfomationActivity.class.getSimpleName();
    private View rl_back;
    private TextView tv_title;
    private EditText edt__product_name;
    private EditText edt__product_quatity;
    private EditText edt_hateromorphism;
    private RelativeLayout rl_unit;
    private View view_unit;
    private TextView edt__unit;
    private ImageView img_unit;
    private EditText edt_length, edt_hight, edt_diametra, edt_thickness;
    private CheckBox cb_hateromorphism;
    private RelativeLayout rl_schematic_diagram;
    private ImageView img_schematic_diagram;
    private Button btn_upload;

    private PopupWindow mPopupWindow;

    private String unit = "套";
    private int diameterInt, heightInt, thickInt, lenghtInt, amountInt;
    private boolean isCheckBox;

    private List<String> picUrl;
    //    private String picUrl1;
    private String serverUrl;
    private String filePath;
    private UploadPhotoPresenter uploadPhotoPresenter;

    private AddProductInforPoupWindow addProductInforPoupWindow;
    private String datas[] = {"套", "只", "个", "箱", "件", "台", "条"};

    @Override
    protected void onBaseCreate(Bundle savedInstanceState) {
        setContentView(R.layout.layout_add_product_infomation1);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        edt__product_name = findViewById(R.id.edt__product_name);
        edt__product_quatity = findViewById(R.id.edt__product_quatity);
        view_unit = findViewById(R.id.view_unit);
        edt__unit = findViewById(R.id.edt__unit);
        img_unit = findViewById(R.id.img_unit);
        rl_unit = findViewById(R.id.rl_unit);
        edt_length = findViewById(R.id.edt_length);
        edt_hight = findViewById(R.id.edt_hight);
        edt_diametra = findViewById(R.id.edt_diametra);
        edt_thickness = findViewById(R.id.edt_thickness);
        edt_hateromorphism = findViewById(R.id.edt_hateromorphism);
        cb_hateromorphism = findViewById(R.id.cb_hateromorphism);
        rl_schematic_diagram = findViewById(R.id.rl_schematic_diagram);
        img_schematic_diagram = findViewById(R.id.img_schematic_diagram);
        btn_upload = findViewById(R.id.btn_upload);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        tv_title.setText("编辑产品信息");

        Intent intent = getIntent();
        if ("engineeringInstall".equals(intent.getStringExtra("type"))
                || "engineeringInfomartion".equals(intent.getStringExtra("type"))) {
            rl_schematic_diagram.setVisibility(View.GONE);
            edt_hateromorphism.setVisibility(View.INVISIBLE);
        }
        if ("engineeringConstruct".equals(intent.getStringExtra("type"))
                || "productionTaskOrder".equals(intent.getStringExtra("type"))) {
            rl_schematic_diagram.setVisibility(View.VISIBLE);
            edt_hateromorphism.setVisibility(View.VISIBLE);
        }

        uploadPhotoPresenter = new UploadPhotoPresenter(this);
    }

    @Override
    public void setListener() {
        rl_back.setOnClickListener(this);
        img_unit.setOnClickListener(this);
        cb_hateromorphism.setOnCheckedChangeListener(this);
        btn_upload.setOnClickListener(this);
        img_schematic_diagram.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View view) {
        switch (view.getId()) {
            // 返回
            case R.id.rl_back:
                finish();
                break;
            // 上传
            case R.id.btn_upload:
                upload();
                break;
            // 图片
            case R.id.img_schematic_diagram:
                showListDialog();
                break;
            // 单位
            case R.id.img_unit:
                hideSoftInputView();
                showUnitWindow(view_unit);
//                View contentView = LayoutInflater.from(this).inflate(R.layout.item_add_product_infor, null);
//                TextView tao = (TextView) contentView.findViewById(R.id.tao);
//                TextView zhi = (TextView) contentView.findViewById(R.id.zhi);
//                TextView ge = (TextView) contentView.findViewById(R.id.ge);
//                TextView xiang = (TextView) contentView.findViewById(R.id.xiang);
//                TextView jian = (TextView) contentView.findViewById(R.id.jian);
//                TextView tai = (TextView) contentView.findViewById(R.id.tai);
//                TextView tiao = (TextView) contentView.findViewById(R.id.tiao);
//
//                tao.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("套");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                zhi.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("只");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                ge.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("个");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                xiang.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("箱");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                jian.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("件");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                tai.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("台");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                tiao.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        edt__unit.setText("tiao");
//                        mPopupWindow.dismiss();
//                    }
//                });
//
//                mPopupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
//                mPopupWindow.setTouchable(true);
//                /* 设置点击menu以外其他地方以及返回键退出 */
//                mPopupWindow.setFocusable(true);
//                // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
//                mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
//                mPopupWindow.showAsDropDown(view);
                break;
        }
    }

    // 单位
    private void showUnitWindow(View anchor) {
        addProductInforPoupWindow = new AddProductInforPoupWindow(this, datas);
        addProductInforPoupWindow.setItemClick(this);
        addProductInforPoupWindow.showPopupWindow(anchor);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.cb_hateromorphism:
                if (isChecked) {// true
                    isCheckBox = isChecked;
                } else {// false
                    isCheckBox = isChecked;
                }
                break;
        }
    }

    @Override
    public void onItemDialogClick(DialogItemBean item) {
        switch (item.getmTextId()) {
            case R.string.camera: {
                PhotoUtil.startCamear(ProduceAddProductInfomationActivity.this, null);
                break;
            }
            case R.string.gallary: {
                PhotoUtil.startGallery(ProduceAddProductInfomationActivity.this, null);
                break;
            }
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case PhotoUtil.CAMERA:
                if (resultCode == RESULT_OK) {
                    File picture = new File(PhotoUtil.filePath);
                    if (!picture.exists()) {
                        picture = new File(PhotoUtil.filePath);
                    }

                    filePath = PhotoUtil.CAMERA_SEVER + picture.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(picture.getAbsolutePath(), filePath);

                    Log.e(TAG, "----filePath=" + filePath);

                    picUrl = new ArrayList<>();
                    picUrl.add(filePath);

//                    picUrl1=filePath;

                    Glide.with(ProduceAddProductInfomationActivity.this).load(new File(filePath)).error(R.drawable.bg_photo_selector).into(img_schematic_diagram);
                    uploadPhotoPresenter.uploadPhtoto();
                }
                break;
            case PhotoUtil.GALLERY:
                if (resultCode == RESULT_OK) {

                    String path = FileUtil.getRealPathFromURI(this, Uri.parse(data.getData() + ""));

                    Log.e(TAG, "----path=" + path);

                    picUrl = new ArrayList<>();
                    picUrl.add(path);

//                    picUrl1=path;

                    Glide.with(ProduceAddProductInfomationActivity.this).load(new File(path)).error(R.drawable.bg_photo_selector).into(img_schematic_diagram);

                    File f = new File(path);
                    filePath = PhotoUtil.CAMERA_SEVER + f.getName();
                    filePath = PhotoUtil.imageCompressionAndSave(path, filePath);
                    uploadPhotoPresenter.uploadPhtoto();
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showListDialog() {
        DialogItemBean[] items = new DialogItemBean[]{
                new DialogItemBean(R.string.camera,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.gallary,
                        R.layout.dialog_list_item_normal),
                new DialogItemBean(R.string.cancel,
                        R.layout.dialog_list_item_normal)};
        BottomListDialog dialog = new BottomListDialog(this, Arrays.asList(items));
        dialog.setItemClick(this);
        dialog.show();
    }

    /**
     * 上传产品信息
     */
    private void upload() {
        String name = edt__product_name.getText().toString().trim();
        String quality = edt__product_quatity.getText().toString().trim();
        if (!TextUtils.isEmpty(quality)) {
            amountInt = Integer.parseInt(quality);
        }
        unit = edt__unit.getText().toString().trim();

        Produce_ProductBean productBean = new Produce_ProductBean();
        productBean.setAmount(amountInt);
        productBean.setProductName(name);
        productBean.setPicUrl(picUrl);
        productBean.setUnit(unit);

        if (TextUtils.isEmpty(edt__product_name.getText().toString())) {
            Toast.makeText(this, "请输入产品名称", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(edt__product_quatity.getText().toString())) {
            Toast.makeText(this, "请输入安装数量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (false == isCheckBox
                && TextUtils.isEmpty(edt_length.getText().toString().trim())
                && TextUtils.isEmpty(edt_hight.getText().toString().trim())
                && TextUtils.isEmpty(edt_thickness.getText().toString().trim())
                && TextUtils.isEmpty(edt_diametra.getText().toString().trim())) {
            Toast.makeText(this, "请输入规格尺寸", Toast.LENGTH_SHORT).show();
        } else {
            //矩形
            if (!TextUtils.isEmpty(edt_length.getText().toString().trim())
                    && !TextUtils.isEmpty(edt_hight.getText().toString().trim())
                    && !TextUtils.isEmpty(edt_thickness.getText().toString().trim())
                    && TextUtils.isEmpty(edt_diametra.getText().toString().trim())
                    && false == isCheckBox) {


                lenghtInt = Integer.parseInt(edt_length.getText().toString().trim());
                heightInt = Integer.parseInt(edt_hight.getText().toString().trim());
                thickInt = Integer.parseInt(edt_thickness.getText().toString().trim());

                productBean.getShapeType().setWidth(lenghtInt);
                productBean.getShapeType().setHeight(heightInt);
                productBean.getShapeType().setThick(thickInt);
                productBean.getShapeType().setType(CommonEnum.ProductShapeType.RECTANGLE);
                productBean.setShapeMap(isCheckBox);

//                productBean.setDesc("长" + edt_length.getText().toString().trim()
//                        + "mm*高" + edt_hight.getText().toString().trim()
//                        + "mm*厚" + edt_thickness.getText().toString().trim() + "mm");
//                productBean.setType(CommonEnum.ProductShapeType.SPECIALSHAPE);

                Intent mIntent = new Intent();
                mIntent.putExtra(ConstantUtil.PRODUCTBEAN, productBean);
                setResult(ConstantUtil.ADD_PRODUCT_INFOMATION, mIntent);
                Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            // 圆形
            if (!TextUtils.isEmpty(edt_diametra.getText().toString().trim())
                    && !TextUtils.isEmpty(edt_thickness.getText().toString().trim())
                    && TextUtils.isEmpty(edt_length.getText().toString().trim())
                    && TextUtils.isEmpty(edt_hight.getText().toString().trim())
                    && false == isCheckBox) {

                diameterInt = Integer.parseInt(edt_diametra.getText().toString().trim());
                thickInt = Integer.parseInt(edt_thickness.getText().toString().trim());

                productBean.getShapeType().setDiameter(diameterInt);
                productBean.getShapeType().setThick(thickInt);
                productBean.getShapeType().setType(CommonEnum.ProductShapeType.ROUND);
                productBean.setShapeMap(isCheckBox);

//                productBean.setDesc("直径" + edt_diametra.getText().toString().trim() + "mm*厚" + edt_thickness.getText().toString().trim() + "mm");
//                productBean.setType(CommonEnum.ProductShapeType.SPECIALSHAPE);

                Intent mIntent = new Intent();
                mIntent.putExtra(ConstantUtil.PRODUCTBEAN, productBean);
                setResult(ConstantUtil.ADD_PRODUCT_INFOMATION, mIntent);
                Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                finish();
            }

            // 异形
            if (true == isCheckBox) {
                productBean.getShapeType().setDesc("具体规格尺寸见图纸");
                productBean.getShapeType().setType(CommonEnum.ProductShapeType.SPECIALSHAPE);
                productBean.setShapeMap(isCheckBox);

                Intent mIntent = new Intent();
                mIntent.putExtra(ConstantUtil.PRODUCTBEAN, productBean);
                setResult(ConstantUtil.ADD_PRODUCT_INFOMATION, mIntent);
                Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isCheckBox = false;
    }


    @Override
    public String getFilePath() {
        return filePath;
    }

    @Override
    public void upLoadPhotoSuccessed(String uri) {
        serverUrl = uri;
    }

    @Override
    public void upLoadPhotoFailed(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void itemClick(View view, int position) {
        edt__unit.setText(datas[position]);
    }
}
